﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Controls_General_BreadCrumbs : System.Web.UI.UserControl
{
	public string TailName { get; set; }
	public int Level { get; set; }
	private string url;
	private List<KeyValuePair<int,PageCrumb>> crumbList;

    protected void Page_Load(object sender, EventArgs e)
    {
		
    }

	public void LoadData(int level, string tailName)
	{
		Level = level;
		TailName = tailName;

		if (Level <= 0)
			Level = 1;

		SetDefaultValues();

		crumbList = GetCrumbList();

		ModifyList();
		SaveCrumbList();
		DisplayCrumbs();

	}

	private void DisplayCrumbs()
	{
		repCrumbs.DataSource = crumbList;
		repCrumbs.DataBind();
	}

	private void ModifyList()
	{
		RemoveLowerLevelCrumbs();
		var crumb = new PageCrumb(TailName, Level, Request.RawUrl);	
		if(crumbList.Count == 0 && crumb.Level != 1)
			crumbList.Add(new KeyValuePair<int, PageCrumb>(1, GetDefaultCrumb()));
		else crumbList.Add(new KeyValuePair<int, PageCrumb>(Level, crumb));
	}

	
	private void RemoveLowerLevelCrumbs()
	{
		crumbList.RemoveAll(c => c.Key >= Level);
	}

	private List<KeyValuePair<int, PageCrumb>> GetCrumbList()
	{
		if (Session["breadcrumbs"] == null)
			return new List<KeyValuePair<int, PageCrumb>>();

		return (List<KeyValuePair<int, PageCrumb>>)Session["breadcrumbs"];
	}

	private void SaveCrumbList()
	{
		Session["breadcrumbs"] = crumbList;		
	}

	private void SetDefaultValues()
	{
		if (Level == 0)
			Level = 1;
		if (string.IsNullOrEmpty(TailName))
			TailName = "Untitled";
	}
	
	private PageCrumb GetDefaultCrumb()
	{
		return new PageCrumb("Dashboard", 1, "/");
	}


	class PageCrumb
	{
		public int Level { get; set; }
		public string Name { get; set; }
		public string Url { get; set; }

		public PageCrumb(string name, int level, string url)
		{
			Name = name;
			Level = level;
			Url = url;
		}
	}
}